package cc.yaomm.common.basic.web.intercept;

import cc.yaomm.common.basic.constant.DefaultConstant;
import cc.yaomm.common.basic.lang.bo.BaseLoginBO;
import cc.yaomm.common.basic.util.TokenUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>@Description : 登录信息拦截器</p>
 * <p>@Author : QiLin.Xing </p>
 * <p>@Date : 2018/11/30 15:34 </p>
 * TODO
 */
@Slf4j
public class TokenIntercept<T extends BaseLoginBO> implements HandlerInterceptor {

    //用户登录信息
    private Class<T> clazz;

    //token工具类
    private TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object handler) {

        String tokenStr = httpServletRequest.getHeader(DefaultConstant.HEADER_TOKEN);

        //判断客户端是否传递了TOKEN
        if (StringUtils.isNotBlank(tokenStr) && !"null".equalsIgnoreCase(tokenStr)) {
            //token不为空
            String tokenValue = tokenUtils.getToken(tokenStr);
            if (StringUtils.isNotBlank(tokenValue)) {
                //验证TOKEN通过
                try {
                    BaseLoginBO loginBO = JSON.parseObject(tokenValue, clazz);
                    httpServletRequest.setAttribute(DefaultConstant.USER_LOGIN_INFO, loginBO);
                    httpServletRequest.setAttribute(DefaultConstant.REQUEST_UID, loginBO.getMessage());
                } catch (Exception e) {
                    log.warn("解析用户登录信息失败，token:[{}],value:[{}]", tokenStr, tokenValue);
                }
            }
        }
        return Boolean.TRUE;
    }
}
